package pattern.Composite;

import java.util.ArrayList;
import java.util.LinkedHashSet;

/**
 * Pipe
 * Create on 2017/5/10
 *
 * @author Asin Liu
 * @version 1.0
 */
public class Pipe {

    // 字典，相当于流入管道的数据流
    private Dictionary dictionary;

    // 用于保存过滤后的最终数据
    private LinkedHashSet<String> theWords;

    // 单词查询中需要用到的过滤器树
    private IFilter filterTree;

    // 用于保存字典中的所有单词，即数据流中的一个个数据
    private ArrayList<String> allWords;

    public Pipe(Dictionary dictionary, IFilter filterTree) {
        this.dictionary = dictionary;
        this.filterTree = filterTree;
        this.theWords = new LinkedHashSet<String>();
    }

    public LinkedHashSet<String> getWords() {
        // 先搜索过滤字典中所有单词，再返回符合要求的单词集合
        this.allWords = dictionary.getAllWords();
        this.findWords();
        return this.theWords;
    }

    private void findWords() {
        // 对每个单词进行过滤
        for (String word : allWords) {
            if (filterTree.match(word) == true) {
                this.theWords.add(word);
            }
        }
    }
}
